const puppeteer = require("puppeteer-extra");
const StealthPlugin = require("puppeteer-extra-plugin-stealth");
const fs = require("fs");
const config = require("../config");
const utils = require('../utils');
puppeteer.use(StealthPlugin());
module.exports = async (sellerId) => {
  // 判断文件夹是否存在，如果不存在则创建
  if (!fs.existsSync(`./data/${sellerId}`)) {
    fs.mkdirSync(`./data/${sellerId}`);
  }
  // 判断文件是否存在，如果不存在则创建
  if (!fs.existsSync(`./data/${sellerId}/${sellerId}.txt`)) {
    fs.writeFileSync(`./data/${sellerId}/${sellerId}.txt`, '');
  }
  puppeteer
    .launch({
      headless: false,
      // args: ["--no-sandbox", "--disable-setuid-sandbox"],
      defaultViewport: {
        width: 1920,
        height: 1080,
      },
    })
    .then(async (browser) => {
      const page = await browser.newPage();
      page.setDefaultNavigationTimeout(3000000);

      // ------第一步 获得新的token-------------//
      // 进入amazon.com，修改邮编
      await page.goto(config.webSite + "dp/B0C6J61DDD");
      // 打开切换邮编弹窗
      await page.waitForSelector("#nav-global-location-data-modal-action");
      await page.click("#nav-global-location-data-modal-action");
      // 填写其他地址字段,洛杉矶
      await page.waitForSelector("#GLUXZipUpdateInput");
      await page.$eval(
        "#GLUXZipUpdateInput",
        (el, address) => (el.value = address),
        config.address
      );
      await page.waitForSelector("#GLUXZipUpdate");
      const hasClickBtn = await page.evaluate(() => {
        return !!document.querySelector("#GLUXZipUpdate-announce");
      });

      if (hasClickBtn) {
        await page.click("#GLUXZipUpdate-announce");
        await page.click("#GLUXZipUpdate");
      } else {
        await page.click("#GLUXZipUpdate");
        await page.click("#GLUXZipUpdate-announce");
      }

      await utils.sleep(1000);

      // 开始执行任务
      let index = 1;
      let infos = [];
      await getStoreAsins();
      const infoData = JSON.stringify(infos, null, 2);
      
      fs.readFile(`./data/${sellerId}/${sellerId}.txt`, "utf-8", (err, info) => {
        if (err) {
          fs.writeFileSync(`./data/${sellerId}/${sellerId}.txt`, infoData);
        } else {
          fs.writeFileSync(`./data/${sellerId}/${sellerId}.txt`, info + infoData);
        }
      });

      // 完成所有操作，关闭浏览器
      await browser.close();

      // 获得店铺asin列表
      async function getStoreAsins() {
        await page.goto(
          `${config.webSite}s?me=${sellerId}&page=${index}&marketplaceID=${config.marketplaceId}`
        );
        await page.waitForSelector("body");

        await page.waitForSelector(
          "[data-component-type=s-search-results] div.s-main-slot > [data-index] .sg-col-inner [cel_widget_id] div > div > div > h2> a > span"
        );

        let res = await page.evaluate(async () => {
          let resultProductData = [];
          const productName = document.querySelectorAll(
            "[data-component-type=s-search-results] div.s-main-slot > [data-index] .sg-col-inner [cel_widget_id] div > div > div > h2> a > span"
          );
          const productImage = document.querySelectorAll(
            "[data-component-type=s-search-results] div.s-main-slot > [data-index] .sg-col-inner [cel_widget_id] div > div > span > a > div > img"
          );
          const productPrice = document.querySelectorAll(
            "[data-component-type=s-search-results] div.s-main-slot > [data-index] .sg-col-inner [cel_widget_id] div > div > div > div > a > .a-price > .a-offscreen"
          );
          const productLink = document.querySelectorAll(
            "[data-component-type=s-search-results] div.s-main-slot > [data-index] .sg-col-inner [cel_widget_id] div > div > span > a"
          );

          // const reviews = document.querySelectorAll(
          //   "[data-component-type=s-search-results] div.s-main-slot > [data-index] .sg-col-inner [cel_widget_id] div > span > a > i"
          // );
          const asins = document.querySelectorAll(
            "[data-component-type=s-search-results] div.s-main-slot > [data-index].s-asin"
          );

          for (const [index, product] of productName.entries()) {
            resultProductData.push({
              asin: asins[index].dataset.asin,
              title: product.innerText,
              image: productImage[index].src,
              price: productPrice[index].innerText.replace("$", "").trim(),
              link: productLink[index].href,
              // review: 1
            });
          }
          return {
            list: resultProductData,
            hasNext:
              document.body.querySelector(".s-pagination-next") &&
              !document.body.querySelector(
                ".s-pagination-next.s-pagination-disabled"
              ),
          };
        });

        infos = infos.concat(res.list);

        // 递归执行任务
        if (res.hasNext) {
          index++;
          console.log(`------第${index}正在获取------`);
          utils.sleep(Math.floor(Math.random() * (1500 - 500) + 500));
          await getStoreAsins();
        }
      }
    });
}